require('bytenode');
const { app, BrowserWindow, Tray, Menu, ipcMain } = require('electron');
const koaApp = require(__dirname+'/app'); // 引入Koa2服务模块
const exeRoot = process.cwd(); // 获取当前执行根目录
// __dirname; // 获取当前执行目录

let mainWindow;
let tray;
var kill = false;
var port = 3001;

ipcMain.on('message-to-index', (event, message) => {
    console.log('来自web端的消息：',message);
});
function createWindow() {
    Menu.setApplicationMenu(null); // null值取消顶部菜单栏
    mainWindow = new BrowserWindow({
        width: 1300,
        height: 768,
        webPreferences: {
            nodeIntegration: true,
            devTools: true, //调试模式
            preload: __dirname+ '/preload.js', // 预加载js文件 使web页面可以使用electron的api
        },
        icon: __dirname + '/public/favicon.png', //窗口图标
        // titleBarStyle: 'hidden',
        // fullscreen: true,
        // frame: false, // 无边框
        // transparent: true, // 背景透明
        // alwaysOnTop:true, // 窗口置顶
        // closable:true, // 窗口不能关闭
    });

    // mainWindow.loadURL('http://localhost:'+port); // 加载Koa2服务器的地址
    mainWindow.loadURL(__dirname+'/test.html');

    mainWindow.on('close', (e) => {
        if (!kill) {
            // 阻止默认的关闭操作
            e.preventDefault();
            closeWindow()
        }
    });
}

function createTray() {
    tray = new Tray(__dirname + '/public/favicon.png'); // 托盘图标
    const contextMenu = Menu.buildFromTemplate([
        { label: '显示', click: () => { mainWindow ? mainWindow.show() : createWindow(); } },
        {
            label: '退出', click: () => {
                kill = true;
                app.quit();
            }
        }
    ]);
    tray.setContextMenu(contextMenu);
    // 双击托盘图标显示窗口
    tray.on('double-click', () => {
        if (mainWindow) {
            mainWindow.show();
        } else {
            createWindow();
        }
    });
}
function closeWindow() {
    if (mainWindow) {
        // mainWindow.setSkipTaskbar(true);
        mainWindow.hide();
        // mainWindow = null;
    }
}

function startServer() {
    return new Promise((resolve, reject) => {
        const server = koaApp.listen(port, () => {
            console.log(`Server listening on port ${port}`);
            resolve(server);
        });

        server.on('error', (err) => {
            if (err.code === 'EADDRINUSE') {
                console.log(`Port ${port} is in use, trying another port...`);
                port += 1;
                startServer().then(resolve).catch(reject);
            } else {
                reject(err);
            }
        });
    });
}

app.whenReady().then(() => {
    koaApp.use(require('koa-static')(exeRoot + '/public'));// 针对/pubilic/upimg/添加静态资源
    startServer().then(() => {
        createWindow();
        createTray();
    })
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
});

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') {
        app.quit(); //关闭按钮完全退出应用
    }
});
